<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useExhibitionStore } from '../../store/exhibition/exhibitionStore'
import { useExhibitionOrderStore } from '../../store/exhibition/exhibitionOrderStore'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Calendar, Tickets, SetUp, Edit, Plus, Minus, Money, PriceTag } from '@element-plus/icons-vue'
import Exhibition from '../../api/exhibition'

const route = useRoute()
const exhibitionStore = useExhibitionStore()
const orderStore = useExhibitionOrderStore()

// 批量设置相关
const batchDialogVisible = ref(false)
const batchType = ref('all')
const batchTickets = ref(20)
const batchOptions = [
    { label: '所有日期', value: 'all' },
    { label: '工作日', value: 'weekday' },
    { label: '周末', value: 'weekend' },
    { label: '节假日', value: 'holiday' }
]

// 票价设置相关
const priceDialogVisible = ref(false)
const defaultPrice = ref(0)
const priceSettingType = ref('default') // default: 默认票价, daily: 每日票价, type: 票价类型
const selectedDateIndex = ref(0)

// 加载状态
const isLoading = ref(false)

// 加载展览数据
const loadExhibitionData = async () => {
    try {
        // 重置状态，清除之前的数据
        orderStore.resetState()

        // 如果路由中有展览ID，则获取该展览信息
        const exhibitionId = route.params.id
        console.log('exhibitionId:', exhibitionId)

        if (exhibitionId) {
            // 获取展览详情
            await Exhibition.getExhibitionById(exhibitionId).then((res) => {
                if (res.data.code === 200) {
                    // 检查展览数据是否有效
                    if (!res.data.data) {
                        ElMessage.error('展览数据无效')
                        return
                    }

                    orderStore.setCurrentExhibition(res.data.data)
                    console.log('currentExhibition:', orderStore.currentExhibition)
                } else {
                    ElMessage.error('未找到展览信息')
                }
            })
        } else {
            // 如果没有指定展览ID，则获取第一个展览
            await exhibitionStore.getExhibitionList()
            if (exhibitionStore.exhibitions.length > 0) {
                orderStore.setCurrentExhibition(exhibitionStore.exhibitions[0])
            }
        }
    } catch (error) {
        console.error('加载展览数据失败:', error)
        ElMessage.error('加载展览数据失败')
    }
}

// 监听路由参数变化
watch(
    () => route.params.id,
    (newId, oldId) => {
        if (newId !== oldId) {
            loadExhibitionData()
        }
    }
)

//监听票数变化
watch(
    () => orderStore.ticketData,
    (newData, oldData) => {
        if (newData !== oldData) {
            // 计算总票数
            orderStore.calculateTotalTickets()
        }
    },
    { deep: true }
)

// 保存票数据
const saveTicketData = async () => {
    try {
        await orderStore.saveTicketData()
        ElMessage.success('保存成功')
    } catch (error) {
        console.error('保存票数据失败:', error)
        ElMessage.error('保存票数据失败')
    } finally {
        orderStore.changeLoading()
    }
}

// 批量设置票数
const handleBatchUpdate = () => {
    orderStore.batchUpdateTickets(batchType.value, batchTickets.value)
    batchDialogVisible.value = false
    ElMessage.success('批量设置成功')
}

// 打开票价设置对话框
const openPriceDialog = (type, index) => {
    priceSettingType.value = type
    if (type === 'daily') {
        selectedDateIndex.value = index
        defaultPrice.value = orderStore.ticketData[index].ticketPrice || orderStore.defaultTicketPrice
    } else {
        defaultPrice.value = orderStore.defaultTicketPrice
    }
    priceDialogVisible.value = true
}

// 保存票价设置
const savePriceSetting = () => {
    if (priceSettingType.value === 'daily') {
        // 设置单日票价
        orderStore.updateDailyTicketPrice(selectedDateIndex.value, defaultPrice.value)
    } else if (priceSettingType.value === 'batch') {
        // 批量设置票价
        orderStore.batchUpdateTicketPrice(batchType.value, defaultPrice.value)
    } else {
        // 设置默认票价
        orderStore.updateTicketPrices(defaultPrice.value)
    }
    priceDialogVisible.value = false
    ElMessage.success('票价设置成功')
}

// 增加票数
const increaseTickets = (index) => {
    const currentTickets = orderStore.ticketData[index].availableTickets
    orderStore.updateDailyTickets(index, currentTickets + 10)
    orderStore.calculateTotalTickets()
}

// 减少票数
const decreaseTickets = (index) => {
    const currentTickets = orderStore.ticketData[index].availableTickets
    if (currentTickets >= 10) {
        orderStore.updateDailyTickets(index, currentTickets - 10)
    } else {
        orderStore.updateDailyTickets(index, 0)
    }
    orderStore.calculateTotalTickets()
}

// 展览日期范围
const dateRange = computed(() => {
    if (!orderStore.currentExhibition) return ''
    const startDate = new Date(orderStore.currentExhibition.startTime || new Date())

    // 处理 endTime 为 null 的情况
    if (!orderStore.currentExhibition.endTime) {
        return `${startDate.getFullYear()}-${String(startDate.getMonth() + 1).padStart(2, '0')}-${String(startDate.getDate()).padStart(2, '0')} 起（常设展览）`
    }

    const endDate = new Date(orderStore.currentExhibition.endTime)
    return `${startDate.getFullYear()}-${String(startDate.getMonth() + 1).padStart(2, '0')}-${String(startDate.getDate()).padStart(2, '0')} 至 ${endDate.getFullYear()}-${String(endDate.getMonth() + 1).padStart(2, '0')}-${String(endDate.getDate()).padStart(2, '0')}`
})

// 获取日期类型标签
const getDateTypeTag = (item) => {
    if (item.isHoliday) return { type: 'danger', label: '节假日' }
    if (item.isWeekend) return { type: 'warning', label: '周末' }
    return { type: 'success', label: '工作日' }
}

// 组件挂载时加载数据
onMounted(() => {
    loadExhibitionData()
})
</script>

<template>
    <div class="exhibition-order-container">
        <!-- 头部信息 -->
        <el-card class="header-card" v-if="orderStore.currentExhibition">
            <template #header>
                <div class="card-header">
                    <h2>{{ orderStore.currentExhibition.name }} - 预约票管理</h2>
                    <div class="header-actions">
                        <el-button type="primary" @click="batchDialogVisible = true" :icon="SetUp">批量设置票数</el-button>
                        <!--<el-button type="warning" @click="openPriceDialog('default')" :icon="Money">设置票价</el-button>-->
                        <el-button type="success" @click="saveTicketData" :icon="Tickets">保存设置</el-button>
                    </div>
                </div>
            </template>
            <div class="exhibition-info">
                <div class="info-item">
                    <el-icon>
                        <Calendar />
                    </el-icon>
                    <span>展览日期: {{ dateRange }}</span>
                </div>
                <div class="info-item">
                    <el-icon>
                        <Tickets />
                    </el-icon>
                    <span>总票数: {{ orderStore.totalTickets }}</span>
                </div>

            </div>


        </el-card>

        <!-- 加载中 -->
        <div v-if="orderStore.loading" class="loading-container">
            <el-skeleton :rows="10" animated />
        </div>

        <!-- 票数设置列表 -->
        <el-card v-else-if="orderStore.ticketData.length > 0" class="tickets-card">
            <template #header>
                <div class="tickets-header">
                    <h3>每日票数与票价设置</h3>
                    <div class="tickets-actions-button">
                        <div class="tickets-actions">
                            <el-button type="warning" size="small" @click="openPriceDialog('batch')"
                                :icon="Money">批量设置票价</el-button>
                        </div>
                        <div class="t">
                            <el-button type="warning" size="small" @click="orderStore.newTicketData"
                                :icon="Money">新增时间</el-button>
                        </div>
                    </div>
                </div>
            </template>
            <div class="tickets-grid">
                <div v-for="(item, index) in orderStore.ticketData" :key="index" class="ticket-item">
                    <div class="ticket-date">
                        <div class="date-value">{{ item.formattedDate }}</div>
                        <el-tag size="small" :type="getDateTypeTag(item).type">{{ getDateTypeTag(item).label }}</el-tag>
                    </div>
                    <div class="ticket-price">
                        <span class="price-label">票价:</span>
                        <span class="price-value">¥{{ item.ticketPrice || orderStore.defaultTicketPrice }}</span>
                        <el-button type="primary" size="small" text @click="openPriceDialog('daily', index)">
                            <el-icon>
                                <Edit />
                            </el-icon>
                        </el-button>
                    </div>
                    <div class="ticket-price">
                        <span class="tickets-label">已售出票数：</span>
                        <span class="total-value">{{ item.paidNumber }}</span>
                    </div>
                    <div class="ticket-control">
                        <span class="tickets-label">总票数：</span>
                        <div class="tickets-input-group">
                            <el-button circle :icon="Minus" @click="decreaseTickets(index)"
                                :disabled="item.availableTickets <= 0" />
                            <el-input-number v-model="item.availableTickets" :min="0" :max="1000" size="small"
                                controls-position="right" />
                            <el-button circle :icon="Plus" @click="increaseTickets(index)" />
                        </div>
                    </div>
                </div>
            </div>
        </el-card>

        <!-- 无数据提示 -->
        <el-empty v-else description="暂无展览数据" />

        <!-- 批量设置票数对话框 -->
        <el-dialog v-model="batchDialogVisible" title="批量设置预约票" width="400px">
            <el-form label-width="100px">
                <el-form-item label="设置类型">
                    <el-select v-model="batchType" placeholder="请选择设置类型">
                        <el-option v-for="item in batchOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="票数">
                    <el-input-number v-model="batchTickets" :min="0" :max="1000" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="batchDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleBatchUpdate">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 票价设置对话框 -->
        <el-dialog v-model="priceDialogVisible"
            :title="priceSettingType === 'daily' ? '设置单日票价' : priceSettingType === 'batch' ? '批量设置票价' : '设置默认票价'"
            width="400px">
            <el-form label-width="100px">
                <el-form-item v-if="priceSettingType === 'batch'" label="设置类型">
                    <el-select v-model="batchType" placeholder="请选择设置类型">
                        <el-option v-for="item in batchOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item
                    :label="priceSettingType === 'daily' ? '单日票价' : priceSettingType === 'batch' ? '批量票价' : '默认票价'">
                    <el-input-number v-model="defaultPrice" :min="0" :precision="2" :step="10" style="width: 100%">
                        <template #prefix>
                            <el-icon>
                                <Money />
                            </el-icon>
                        </template>
                        <template #suffix>元</template>
                    </el-input-number>
                </el-form-item>
                <el-form-item v-if="priceSettingType === 'default'" label="说明">
                    <el-alert title="设置默认票价后，所有票价类型将按照折扣比例自动计算" type="info" :closable="false" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="priceDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="savePriceSetting">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.exhibition-order-container {
    padding: 20px;
}

.header-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-header h2 {
    margin: 0;
    font-size: 18px;
    color: #303133;
}

.header-actions {
    display: flex;
    gap: 10px;
}

.exhibition-info {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    padding: 10px;
}

.info-item {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #606266;
}

/* 票价类型样式 */
.ticket-types {
    margin-bottom: 20px;
    padding: 10px;
}

.ticket-types h3 {
    font-size: 16px;
    margin-bottom: 15px;
    color: #303133;
}

.ticket-type-list {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
}

.ticket-type-card {
    width: 200px;
    transition: all 0.3s;

}

.ticket-type-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.ticket-type-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.ticket-type-name {
    font-weight: bold;
    color: #303133;
}

.ticket-type-price {
    margin: 15px 0;
}

.ticket-type-price .price {
    font-size: 24px;
    font-weight: bold;
    color: #f56c6c;
}

.ticket-type-price .discount {
    font-size: 14px;
    color: #909399;
    margin-left: 5px;
}

.ticket-type-actions {
    display: flex;
    justify-content: flex-end;
}

/* 票数设置列表样式 */
.tickets-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.tickets-header h3 {
    margin: 0;
    font-size: 16px;
    color: #303133;
}
.tickets-actions-button{
    display: flex;
    gap: 10px;
}

.tickets-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 320px));
    gap: 50px;
    padding: 10px;
    justify-content: center;
    align-items: center;
}

.ticket-item {
    border: 1px solid #ebeef5;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    transition: all 0.3s;
}

.ticket-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.ticket-date {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.date-value {
    font-weight: bold;
    color: #303133;
}

.ticket-price {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
}

.price-label {
    color: #606266;
    margin-right: 8px;
}

.price-value {
    font-weight: bold;
    color: #f56c6c;
    flex-grow: 1;
}

.ticket-control {
    display: flex;
    align-items: center;
}

.tickets-label {
    color: #606266;
    margin-right: 8px;
}

.tickets-input-group {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    flex-grow: 1;
}

.loading-container {
    padding: 20px;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
    .card-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }

    .header-actions {
        width: 100%;
        justify-content: flex-end;
    }

    .tickets-grid {
        grid-template-columns: 1fr;
    }

    .ticket-type-list {
        flex-direction: column;
    }

    .ticket-type-card {
        width: 100%;
    }
}
</style>